package com.alliky.core.base

import android.content.Context
import com.rrc.common.api.ApiService
import com.rrc.common.entity.BaseResponse
import com.rrc.common.entity.DataState
import com.alliky.core.loader.Loader
import com.alliky.core.net.RetrofitKt
import com.alliky.core.net.StateLiveData
import com.alliky.core.utils.RxUtils


/**
 * ================================================
 * @Description: 描述
 * @Author: wxianing
 * @Date: 2022/11/4 11:57
 * ================================================
 */
open class BaseRepository {

    val service: ApiService by lazy {
        RetrofitKt.getRetrofit()!!.create(ApiService::class.java)
    }


    suspend fun <T : Any> executeResp(
        block: suspend () -> BaseResponse<T>,
        stateLiveData: StateLiveData<T>,
        context: Context?,
        text: String?
    ) {
        var baseResponse = BaseResponse<T>()
        if (context != null) {
            if (!RxUtils.isBlank(text)) {
                Loader.showLoading(context, text)
            } else {
                Loader.showLoading(context);
            }
        }
        try {

            baseResponse.dataState = DataState.STATE_LOADING

            //开始请求数据
            val invoke = block.invoke()
            //将结果复制给baseResp
            baseResponse = invoke

            if (baseResponse.isOk) {
                if (baseResponse.data == null || baseResponse.data is List<*> && (baseResponse.data as List<*>).size == 0) {
                    baseResponse.dataState = DataState.STATE_EMPTY
                } else {
                    baseResponse.dataState = DataState.STATE_SUCCESS
                }
            } else {
                baseResponse.dataState = DataState.STATE_FAILED
            }

        } catch (e: Exception) {
            //非后台返回错误，捕获到的异常
            baseResponse.dataState = DataState.STATE_ERROR
//            var throwable: ResponseThrowable = HandleException.handleException(e)
//            baseResponse.message = throwable.message
//            baseResponse.code = throwable.code
//            errorLiveData.postValue(throwable)
        } finally {
            Loader.stopLoading()
            stateLiveData.postValue(baseResponse)
        }
    }

    suspend fun <T : Any> executeResp(
        block: suspend () -> BaseResponse<T>,
        stateLiveData: StateLiveData<T>,
        context: Context?,
    ) {
        executeResp(block, stateLiveData, context, null)
    }

    /**
     * 方式一
     * repo 请求数据的公共方法，
     * 在不同状态下先设置 baseResp.dataState的值，最后将dataState 的状态通知给UI
     * @param block api的请求方法
     * @param stateLiveData 每个请求传入相应的LiveData，主要负责网络状态的监听
     */
    suspend fun <T : Any> executeResp(
        block: suspend () -> BaseResponse<T>,
        stateLiveData: StateLiveData<T>,
    ) {
        executeResp(block, stateLiveData, null)
    }
}